package com.gongfutrip.trans.client.processor;

import java.io.IOException;
import java.util.Map;

import com.gongfutrip.trans.client.common.ClientUtils;
import com.gongfutrip.trans.client.common.MessageSysFlag;
import com.gongfutrip.trans.remoting.NettyRequestProcessor;
import com.gongfutrip.trans.remoting.protocol.RemotingCommand;

import io.netty.channel.ChannelHandlerContext;

public abstract class Processor implements NettyRequestProcessor {
  public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request)
      throws Exception {
    unCompressBody(request);
    return doRequest(ctx, request);
  }

  private void unCompressBody(RemotingCommand request) throws IOException {
    Map<String, String> extFilelds = request.getExtFields();
    if (null != extFilelds) {// 解压
      if (extFilelds.containsKey("sysFlag")) {
        int sysFlag = Integer.valueOf(extFilelds.get("sysFlag"));
        if (MessageSysFlag.compressed(sysFlag)) {
          request.setBody(ClientUtils.uncompress(request.getBody()));
          extFilelds.put("sysFlag", "" + MessageSysFlag.clearCompressedFlag(sysFlag));
        }
      }
    }
  }

  public boolean rejectRequest() {
    return false;
  }



  public abstract RemotingCommand doRequest(ChannelHandlerContext ctx, RemotingCommand request)
      throws Exception;

  public static void main(String[] args) {
    int COMPRESSED_FLAG = 0x1;
    System.out.println((1 & COMPRESSED_FLAG) == COMPRESSED_FLAG);
    System.out.println(1 & (~COMPRESSED_FLAG));
  }
}
